<template>
  <div class="my-order-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2 class="page-title">
        <el-icon><Tickets /></el-icon>
        我的工单
      </h2>
      <p class="page-desc">管理您创建的所有工单申请</p>
    </div>

    <!-- 快速操作区域 -->
    <div class="quick-actions">
      <el-card class="actions-card" shadow="never">
        <div class="actions-content">
          <div class="action-buttons">
            <el-button type="primary" @click="handleCreateOrder">
              <el-icon><Plus /></el-icon>
              创建工单
            </el-button>
            <el-button type="success" @click="handleBatchExport">
              <el-icon><Download /></el-icon>
              批量导出
            </el-button>
            <el-button @click="handleRefresh">
              <el-icon><Refresh /></el-icon>
              刷新
            </el-button>
          </div>
          <div class="order-stats">
            <div class="stat-item">
              <span class="stat-number">{{ stats.total }}</span>
              <span class="stat-label">总工单</span>
            </div>
            <div class="stat-item">
              <span class="stat-number pending">{{ stats.pending }}</span>
              <span class="stat-label">待审核</span>
            </div>
            <div class="stat-item">
              <span class="stat-number approved">{{ stats.approved }}</span>
              <span class="stat-label">已通过</span>
            </div>
            <div class="stat-item">
              <span class="stat-number rejected">{{ stats.rejected }}</span>
              <span class="stat-label">已拒绝</span>
            </div>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 搜索和筛选区域 -->
    <div class="search-section">
      <el-card class="search-card" shadow="never">
        <el-form :model="searchForm" inline>
          <el-form-item label="工单类型">
            <el-select v-model="searchForm.orderType" placeholder="请选择工单类型" clearable style="width: 180px">
              <el-option label="请假申请" value="leave" />
              <el-option label="报销申请" value="reimbursement" />
              <el-option label="设备申请" value="equipment" />
              <el-option label="其他申请" value="other" />
            </el-select>
          </el-form-item>
          <el-form-item label="工单状态">
            <el-select v-model="searchForm.status" placeholder="请选择状态" clearable style="width: 150px">
              <el-option label="待审核" value="pending" />
              <el-option label="已通过" value="approved" />
              <el-option label="已拒绝" value="rejected" />
            </el-select>
          </el-form-item>
          <el-form-item label="创建时间">
            <el-date-picker
              v-model="searchForm.dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              style="width: 280px"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">
              <el-icon><Search /></el-icon>
              搜索
            </el-button>
            <el-button @click="handleReset">
              <el-icon><Refresh /></el-icon>
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>

    <!-- 工单列表 -->
    <div class="order-list-section">
      <el-card shadow="never">
        <template #header>
          <div class="card-header">
            <span>工单列表</span>
            <div class="header-actions">
              <el-radio-group v-model="viewMode" size="small">
                <el-radio-button label="table">表格视图</el-radio-button>
                <el-radio-button label="card">卡片视图</el-radio-button>
              </el-radio-group>
            </div>
          </div>
        </template>

        <!-- 表格视图 -->
        <div v-if="viewMode === 'table'">
          <el-table 
            :data="orderList" 
            v-loading="loading"
            @selection-change="handleSelectionChange"
            stripe
            style="width: 100%"
          >
            <el-table-column type="selection" width="55" />
            <el-table-column prop="orderNo" label="工单编号" width="150" />
            <el-table-column prop="title" label="工单标题" min-width="200" />
            <el-table-column prop="orderType" label="工单类型" width="120">
              <template #default="{ row }">
                <el-tag :type="getOrderTypeTag(row.orderType)">
                  {{ getOrderTypeText(row.orderType) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="createTime" label="创建时间" width="180" />
            <el-table-column prop="status" label="状态" width="100">
              <template #default="{ row }">
                <el-tag :type="getStatusTag(row.status)">
                  {{ getStatusText(row.status) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="priority" label="优先级" width="100">
              <template #default="{ row }">
                <el-tag :type="getPriorityTag(row.priority)" size="small">
                  {{ getPriorityText(row.priority) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="reviewer" label="审核人" width="120" />
            <el-table-column prop="reviewTime" label="审核时间" width="180" />
            <el-table-column label="操作" width="200" fixed="right">
              <template #default="{ row }">
                <el-button type="primary" size="small" @click="handleView(row)">
                  <el-icon><View /></el-icon>
                  查看
                </el-button>
                <el-button 
                  v-if="row.status === 'pending'" 
                  type="warning" 
                  size="small" 
                  @click="handleEdit(row)"
                >
                  <el-icon><Edit /></el-icon>
                  编辑
                </el-button>
                <el-button 
                  v-if="row.status === 'pending'" 
                  type="danger" 
                  size="small" 
                  @click="handleCancel(row)"
                >
                  <el-icon><Close /></el-icon>
                  取消
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>

        <!-- 卡片视图 -->
        <div v-else class="card-view">
          <el-row :gutter="20">
            <el-col 
              v-for="order in orderList" 
              :key="order.id" 
              :xs="24" 
              :sm="12" 
              :md="8" 
              :lg="6"
            >
              <el-card class="order-card" shadow="hover">
                <div class="order-card-header">
                  <div class="order-type">
                    <el-tag :type="getOrderTypeTag(order.orderType)" size="small">
                      {{ getOrderTypeText(order.orderType) }}
                    </el-tag>
                  </div>
                  <div class="order-status">
                    <el-tag :type="getStatusTag(order.status)" size="small">
                      {{ getStatusText(order.status) }}
                    </el-tag>
                  </div>
                </div>
                <div class="order-card-content">
                  <h4 class="order-title">{{ order.title }}</h4>
                  <p class="order-desc">{{ order.description }}</p>
                  <div class="order-info">
                    <div class="info-item">
                      <span class="label">编号：</span>
                      <span class="value">{{ order.orderNo }}</span>
                    </div>
                    <div class="info-item">
                      <span class="label">创建时间：</span>
                      <span class="value">{{ order.createTime }}</span>
                    </div>
                    <div class="info-item">
                      <span class="label">优先级：</span>
                      <el-tag :type="getPriorityTag(order.priority)" size="small">
                        {{ getPriorityText(order.priority) }}
                      </el-tag>
                    </div>
                  </div>
                </div>
                <div class="order-card-actions">
                  <el-button type="primary" size="small" @click="handleView(order)">
                    查看详情
                  </el-button>
                  <el-button 
                    v-if="order.status === 'pending'" 
                    type="warning" 
                    size="small" 
                    @click="handleEdit(order)"
                  >
                    编辑
                  </el-button>
                  <el-button 
                    v-if="order.status === 'pending'" 
                    type="danger" 
                    size="small" 
                    @click="handleCancel(order)"
                  >
                    取消
                  </el-button>
                </div>
              </el-card>
            </el-col>
          </el-row>
        </div>

        <!-- 分页 -->
        <div class="pagination-wrapper">
          <el-pagination
            v-model:current-page="pagination.current"
            v-model:page-size="pagination.size"
            :page-sizes="[10, 20, 50, 100]"
            :total="pagination.total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
    </div>

    <!-- 创建工单对话框 -->
    <el-dialog 
      v-model="createDialogVisible" 
      title="创建工单" 
      width="800px"
      :close-on-click-modal="false"
    >
      <el-form :model="orderForm" :rules="orderRules" ref="orderFormRef" label-width="100px">
        <el-form-item label="工单类型" prop="orderType">
          <el-select v-model="orderForm.orderType" placeholder="请选择工单类型" style="width: 100%">
            <el-option label="请假申请" value="leave" />
            <el-option label="报销申请" value="reimbursement" />
            <el-option label="设备申请" value="equipment" />
            <el-option label="其他申请" value="other" />
          </el-select>
        </el-form-item>
        <el-form-item label="工单标题" prop="title">
          <el-input v-model="orderForm.title" placeholder="请输入工单标题" />
        </el-form-item>
        <el-form-item label="优先级" prop="priority">
          <el-radio-group v-model="orderForm.priority">
            <el-radio label="low">低</el-radio>
            <el-radio label="medium">中</el-radio>
            <el-radio label="high">高</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="详细描述" prop="description">
          <el-input 
            v-model="orderForm.description" 
            type="textarea" 
            :rows="4"
            placeholder="请详细描述您的申请内容"
          />
        </el-form-item>
        <el-form-item label="附件">
          <el-upload
            action="#"
            :auto-upload="false"
            :on-change="handleFileChange"
            :file-list="fileList"
            multiple
          >
            <el-button type="primary">
              <el-icon><Upload /></el-icon>
              选择文件
            </el-button>
            <template #tip>
              <div class="el-upload__tip">
                支持 jpg/png/pdf 文件，单个文件不超过 10MB
              </div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="createDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitOrder">提交工单</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 查看详情对话框 -->
    <el-dialog 
      v-model="detailDialogVisible" 
      title="工单详情" 
      width="800px"
      :close-on-click-modal="false"
    >
      <div v-if="currentOrder" class="order-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="工单编号">{{ currentOrder.orderNo }}</el-descriptions-item>
          <el-descriptions-item label="工单标题">{{ currentOrder.title }}</el-descriptions-item>
          <el-descriptions-item label="工单类型">
            <el-tag :type="getOrderTypeTag(currentOrder.orderType)">
              {{ getOrderTypeText(currentOrder.orderType) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="优先级">
            <el-tag :type="getPriorityTag(currentOrder.priority)">
              {{ getPriorityText(currentOrder.priority) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ currentOrder.createTime }}</el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="getStatusTag(currentOrder.status)">
              {{ getStatusText(currentOrder.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="审核人">{{ currentOrder.reviewer || '-' }}</el-descriptions-item>
          <el-descriptions-item label="审核时间">{{ currentOrder.reviewTime || '-' }}</el-descriptions-item>
          <el-descriptions-item label="详细描述" :span="2">{{ currentOrder.description }}</el-descriptions-item>
        </el-descriptions>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
          <el-button 
            v-if="currentOrder?.status === 'pending'" 
            type="warning" 
            @click="handleEdit(currentOrder)"
          >
            编辑
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang='ts'>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Tickets, 
  Plus, 
  Download, 
  Refresh, 
  Search, 
  View, 
  Edit, 
  Close,
  Upload
} from '@element-plus/icons-vue'

// 搜索表单
const searchForm = reactive({
  orderType: '',
  status: '',
  dateRange: []
})

// 分页信息
const pagination = reactive({
  current: 1,
  size: 20,
  total: 0
})

// 统计数据
const stats = reactive({
  total: 0,
  pending: 0,
  approved: 0,
  rejected: 0
})

// 数据状态
const loading = ref(false)
const orderList = ref([])
const selectedOrders = ref([])
const viewMode = ref('table')
const createDialogVisible = ref(false)
const detailDialogVisible = ref(false)
const currentOrder = ref(null)
const orderFormRef = ref()
const fileList = ref([])

// 工单表单
const orderForm = reactive({
  orderType: '',
  title: '',
  priority: 'medium',
  description: ''
})

// 表单验证规则
const orderRules = {
  orderType: [{ required: true, message: '请选择工单类型', trigger: 'change' }],
  title: [{ required: true, message: '请输入工单标题', trigger: 'blur' }],
  description: [{ required: true, message: '请输入详细描述', trigger: 'blur' }]
}

// 模拟数据
const mockOrderList = [
  {
    id: 1,
    orderNo: 'WO202412001',
    title: '请假申请',
    orderType: 'leave',
    createTime: '2024-12-01 09:30:00',
    status: 'approved',
    priority: 'high',
    reviewer: '李经理',
    reviewTime: '2024-12-01 10:30:00',
    description: '因家中有事，需要请假3天处理相关事务'
  },
  {
    id: 2,
    orderNo: 'WO202412002',
    title: '设备申请',
    orderType: 'equipment',
    createTime: '2024-12-01 11:00:00',
    status: 'pending',
    priority: 'medium',
    reviewer: '',
    reviewTime: '',
    description: '申请一台新的笔记本电脑用于开发工作，配置要求：i7处理器，16GB内存，512GB固态硬盘'
  },
  {
    id: 3,
    orderNo: 'WO202412003',
    title: '报销申请',
    orderType: 'reimbursement',
    createTime: '2024-12-01 14:20:00',
    status: 'rejected',
    priority: 'low',
    reviewer: '张主管',
    reviewTime: '2024-12-01 15:00:00',
    description: '出差期间的交通和住宿费用报销，总金额1200元'
  }
]

// 获取工单列表
const getOrderList = async () => {
  loading.value = true
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    orderList.value = mockOrderList
    pagination.total = mockOrderList.length
    
    // 更新统计数据
    stats.total = mockOrderList.length
    stats.pending = mockOrderList.filter(item => item.status === 'pending').length
    stats.approved = mockOrderList.filter(item => item.status === 'approved').length
    stats.rejected = mockOrderList.filter(item => item.status === 'rejected').length
  } catch (error) {
    ElMessage.error('获取工单列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.current = 1
  getOrderList()
}

// 重置
const handleReset = () => {
  Object.assign(searchForm, {
    orderType: '',
    status: '',
    dateRange: []
  })
  handleSearch()
}

// 分页处理
const handleSizeChange = (size: number) => {
  pagination.size = size
  getOrderList()
}

const handleCurrentChange = (current: number) => {
  pagination.current = current
  getOrderList()
}

// 选择处理
const handleSelectionChange = (selection: any[]) => {
  selectedOrders.value = selection
}

// 创建工单
const handleCreateOrder = () => {
  Object.assign(orderForm, {
    orderType: '',
    title: '',
    priority: 'medium',
    description: ''
  })
  fileList.value = []
  createDialogVisible.value = true
}

// 提交工单
const submitOrder = async () => {
  if (!orderFormRef.value) return
  
  try {
    await orderFormRef.value.validate()
    ElMessage.success('工单创建成功')
    createDialogVisible.value = false
    getOrderList()
  } catch (error) {
    ElMessage.error('请完善表单信息')
  }
}

// 查看详情
const handleView = (row: any) => {
  currentOrder.value = row
  detailDialogVisible.value = true
}

// 编辑工单
const handleEdit = (_row: any) => {
  ElMessage.info('编辑功能开发中...')
}

// 取消工单
const handleCancel = (_row: any) => {
  ElMessageBox.confirm('确定要取消这个工单吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    ElMessage.success('工单取消成功')
    getOrderList()
  })
}

// 批量导出
const handleBatchExport = () => {
  if (selectedOrders.value.length === 0) {
    ElMessage.warning('请选择要导出的工单')
    return
  }
  ElMessage.success('批量导出成功')
}

// 刷新
const handleRefresh = () => {
  getOrderList()
}

// 文件上传
const handleFileChange = (file: any) => {
  fileList.value.push(file)
}

// 工具函数
const getOrderTypeTag = (type: string) => {
  const map: Record<string, string> = {
    leave: 'warning',
    reimbursement: 'info',
    equipment: 'success',
    other: 'default'
  }
  return map[type] || 'default'
}

const getOrderTypeText = (type: string) => {
  const map: Record<string, string> = {
    leave: '请假申请',
    reimbursement: '报销申请',
    equipment: '设备申请',
    other: '其他申请'
  }
  return map[type] || '未知'
}

const getStatusTag = (status: string) => {
  const map: Record<string, string> = {
    pending: 'warning',
    approved: 'success',
    rejected: 'danger'
  }
  return map[status] || 'default'
}

const getStatusText = (status: string) => {
  const map: Record<string, string> = {
    pending: '待审核',
    approved: '已通过',
    rejected: '已拒绝'
  }
  return map[status] || '未知'
}

const getPriorityTag = (priority: string) => {
  const map: Record<string, string> = {
    high: 'danger',
    medium: 'warning',
    low: 'info'
  }
  return map[priority] || 'default'
}

const getPriorityText = (priority: string) => {
  const map: Record<string, string> = {
    high: '高',
    medium: '中',
    low: '低'
  }
  return map[priority] || '未知'
}

onMounted(() => {
  getOrderList()
})
</script>

<style scoped lang='less'>
.my-order-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;

  .page-header {
    margin-bottom: 20px;
    
    .page-title {
      display: flex;
      align-items: center;
      gap: 8px;
      margin: 0 0 8px 0;
      font-size: 24px;
      font-weight: 600;
      color: #303133;
    }
    
    .page-desc {
      margin: 0;
      color: #909399;
      font-size: 14px;
    }
  }

  .quick-actions {
    margin-bottom: 20px;
    
    .actions-card {
      border-radius: 8px;
      
      .actions-content {
        display: flex;
        justify-content: space-between;
        align-items: center;
        
        .action-buttons {
          display: flex;
          gap: 12px;
        }
        
        .order-stats {
          display: flex;
          gap: 24px;
          
          .stat-item {
            text-align: center;
            
            .stat-number {
              display: block;
              font-size: 24px;
              font-weight: 600;
              color: #303133;
              
              &.pending {
                color: #e6a23c;
              }
              
              &.approved {
                color: #67c23a;
              }
              
              &.rejected {
                color: #f56c6c;
              }
            }
            
            .stat-label {
              font-size: 12px;
              color: #909399;
            }
          }
        }
      }
    }
  }

  .search-section {
    margin-bottom: 20px;
    
    .search-card {
      border-radius: 8px;
      
      :deep(.el-card__body) {
        padding: 20px;
      }
    }
  }

  .order-list-section {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      font-weight: 600;
    }
    
    .card-view {
      .order-card {
        margin-bottom: 20px;
        border-radius: 8px;
        
        .order-card-header {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 12px;
        }
        
        .order-card-content {
          .order-title {
            margin: 0 0 8px 0;
            font-size: 16px;
            font-weight: 600;
            color: #303133;
          }
          
          .order-desc {
            margin: 0 0 12px 0;
            color: #606266;
            font-size: 14px;
            line-height: 1.5;
            display: -webkit-box;
            -webkit-box-orient: vertical;
            -webkit-line-clamp: 2;
            overflow: hidden;
          }
          
          .order-info {
            .info-item {
              display: flex;
              justify-content: space-between;
              align-items: center;
              margin-bottom: 8px;
              
              .label {
                color: #909399;
                font-size: 12px;
              }
              
              .value {
                color: #606266;
                font-size: 12px;
              }
            }
          }
        }
        
        .order-card-actions {
          display: flex;
          gap: 8px;
          margin-top: 12px;
          padding-top: 12px;
          border-top: 1px solid #ebeef5;
        }
      }
    }
    
    .pagination-wrapper {
      display: flex;
      justify-content: center;
      margin-top: 20px;
      padding-top: 20px;
      border-top: 1px solid #ebeef5;
    }
  }

  .order-detail {
    .el-descriptions {
      margin-bottom: 20px;
    }
  }

  .dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 12px;
  }
}
</style>
